package com.byx.chatclient.view.activity.ui.dashboard;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TabHost;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.R;
import com.byx.chatclient.adapter.FriendsListAdapter;
import com.byx.chatclient.adapter.GroupListAdapter;
import com.byx.chatclient.bean.ChildInfo;
import com.byx.chatclient.bean.FriendInfo;
import com.byx.chatclient.bean.Group;
import com.byx.chatclient.bean.GroupChatInfo;
import com.byx.chatclient.bean.GroupInfo;
import com.byx.chatclient.bean.SimpleGroupBean;
import com.byx.chatclient.entity.Constant;
import com.byx.chatclient.entity.Friend;
import com.byx.chatclient.entity.Result;
import com.byx.chatclient.entity.ResultCallback;
import com.byx.chatclient.entity.SimpleFriend;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ActionRequest;
import com.byx.chatclient.http.ApiUrl;
import com.byx.chatclient.view.activity.GroupDetailActivity;
import com.byx.chatclient.view.activity.PersonDetailsActivity;
import com.byx.chatclient.view.activity.main.MainActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * @author Superb
 */

@SuppressLint("NonConstantResourceId")
public class ContactPersonFragment extends Fragment {

    @BindView(R.id.th_dashboard)
    protected TabHost mTabHost;
    @BindView(R.id.lv_dashboard_1)
    protected ListView mTopList;
    @BindView(R.id.elv_friends)
    protected ExpandableListView mElvFriends;
    @BindView(R.id.elv_groups)
    protected ExpandableListView mElvGroups;

    private FriendsListAdapter mFriendAdapter;
    private GroupListAdapter mGroupAdapter;

    private Call<Result<Map<Integer, List<SimpleGroupBean>>>> mGroupCall;
    private Call<Result<List<SimpleFriend>>> mFriendsCall;

    private Unbinder mUnbinder;
    private static final Map<Integer,String> GROUP_ROLE_MAP = new HashMap<Integer,String>(){{
        put(0,"我创建的群聊");
        put(1,"我管理的群聊");
        put(2,"我加入的群聊");
    }};

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        mUnbinder = ButterKnife.bind(this,root);
        return root;
    }

    /**
     * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
     * has returned, but before any saved state has been restored in to the view.
     * This gives subclasses a chance to initialize themselves once
     * they know their view hierarchy has been completely created.  The fragment's
     * view hierarchy is not however attached to its parent at this point.
     *
     * @param view               The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
     * @param savedInstanceState If non-null, this fragment is being re-constructed
     */
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initToolBar();

        mTabHost.setup();
        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("好友").setContent(R.id.view_friend));
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("群聊").setContent(R.id.view_group));

        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("新朋友");
        arrayList.add("群通知");
        ArrayAdapter<String> top = new ArrayAdapter<>(requireContext(),R.layout.support_simple_spinner_dropdown_item,arrayList);
        mTopList.setAdapter(top);
        mTopList.setVisibility(View.GONE);

        initFriendList();
        initGroupList();
        initFriendAdapter();
        initGroupAdapter();
    }

    private void initFriendList() {
        mElvFriends.setOnItemLongClickListener((parent, view, position, id) -> {
            int groupPosition = (int) view.getTag(FriendsListAdapter.GROUP_LAYOUT_RES_ID);
            int childPosition = (int) view.getTag(FriendsListAdapter.CHILD_LAYOUT_RES_ID);
            if (childPosition == -1){
                System.out.println("点击当前:" + groupPosition);
            }
            return false;
        });
        mElvFriends.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
            FriendInfo friendInfo = (FriendInfo) mFriendAdapter.getChild(groupPosition,childPosition);
            RetrofitFactory.getBean(ActionRequest.class)
                    .queryFriendDetailInfo(((ChatApp) requireActivity().getApplication()).getUserPo().getId(), friendInfo.getId())
                    .enqueue(new Callback<Result<Friend>>() {
                        @Override
                        public void onResponse(@NonNull Call<Result<Friend>> call, @NonNull Response<Result<Friend>> response) {
                            Result<Friend> result = response.body();
                            if (result != null && result.getCode().equals(Result.SUCCESS)) {
                                Friend friendDetail = result.getData();
                                Intent intent = new Intent(requireContext(), PersonDetailsActivity.class);
                                intent.putExtra(Constant.INTENT_KEY_FRIEND, friendDetail);
                                intent.putExtra(Constant.INTENT_KEY_IF_FRIEND,200);
                                startActivity(intent);
                            }
                        }

                        @Override
                        public void onFailure(@NonNull Call<Result<Friend>> call, @NonNull Throwable t) {
                            t.printStackTrace();
                        }
                    });
            return false;
        });
    }

    private void initGroupList() {
        mElvGroups.setOnItemLongClickListener((parent, view, position, id) -> {
            int groupPosition = (int) view.getTag(FriendsListAdapter.GROUP_LAYOUT_RES_ID);
            int childPosition = (int) view.getTag(FriendsListAdapter.CHILD_LAYOUT_RES_ID);
            if (childPosition == -1){
                System.out.println("点击当前:" + groupPosition);
            }
            return false;
        });
        mElvGroups.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
            GroupChatInfo groupChatInfo = (GroupChatInfo) mGroupAdapter.getChild(groupPosition, childPosition);
            Intent intent = new Intent(requireContext(), GroupDetailActivity.class);
            intent.putExtra(Constant.GROUP_ID, groupChatInfo.getGroupId());
//            intent.putExtra(Constant.INTENT_KEY_IF_IN_GROUP,200);
            startActivity(intent);
            return false;
        });
    }

    private void initFriendAdapter() {
        if(mFriendAdapter == null){
            mFriendAdapter = new FriendsListAdapter(requireContext());
            mFriendsCall = RetrofitFactory.getBean(ActionRequest.class).queryAllFriends(((ChatApp) requireActivity().getApplication()).getUserPo().getId());
            mFriendsCall.enqueue(new ResultCallback<List<SimpleFriend>>() {
                        @Override
                        public void onResultSuccess(List<SimpleFriend> data) {
                            Map<String,List<ChildInfo>> map = new HashMap<>();
                            for (SimpleFriend friend : data){

                                FriendInfo friendInfo = new FriendInfo();
                                friendInfo.setId(friend.getId());
                                friendInfo.setAvatar(friend.getFriendAvatar());
                                friendInfo.setLoginId(friend.getFriendLoginId());
                                friendInfo.setName(friend.getFriendRemarkName() == null ? friend.getFriendNickName() : friend.getFriendRemarkName());
                                friendInfo.setStatus(friend.getStatus());

                                if (!map.containsKey(friend.getGroupName())){
                                    map.put(friend.getGroupName(),new ArrayList<>());
                                }
                                // TODO: 2021/5/5 此处通过分组名划分分组，可使用分组id
                                Objects.requireNonNull(map.get(friend.getGroupName())).add(friendInfo);
                            }

                            List<GroupInfo> groupInfoList = new ArrayList<>();
                            for (Map.Entry<String,List<ChildInfo>> entry : map.entrySet()){
                                groupInfoList.add(new GroupInfo(entry.getKey(),entry.getValue()));
                            }

                            mFriendAdapter.setFriends(groupInfoList);
                            mElvFriends.setAdapter(mFriendAdapter);
                        }

                        @Override
                        public void onResultFailure(int code, String msg) {

                        }
                    });
        }
    }

    private void initGroupAdapter(){
        if(mGroupAdapter == null){
            mGroupAdapter = new GroupListAdapter(requireContext());
            mGroupCall = RetrofitFactory.getBean(ActionRequest.class).queryUserGroup(ChatApp.getInstance().getUserPo().getId());
            mGroupCall.enqueue(new ResultCallback<Map<Integer, List<SimpleGroupBean>>>() {
                        @Override
                        public void onResultSuccess(Map<Integer, List<SimpleGroupBean>> data) {
                            List<GroupInfo> groupInfoList = new ArrayList<>();
                            for (Map.Entry<Integer,String> entry : GROUP_ROLE_MAP.entrySet()){
                                List<ChildInfo> childInfoList = new ArrayList<>();
                                List<SimpleGroupBean> groupBeans = data.get(entry.getKey());
                                if (groupBeans != null){
                                    for (SimpleGroupBean groupBean : groupBeans){
                                        GroupChatInfo groupChatInfo = new GroupChatInfo();
                                        groupChatInfo.setGroupId(groupBean.getGroupId());
                                        groupChatInfo.setGroupAvatar(groupBean.getGroupAvatar());
                                        groupChatInfo.setGroupName(groupBean.getGroupName());
                                        childInfoList.add(groupChatInfo);
                                    }
                                }

                                groupInfoList.add(new GroupInfo(GROUP_ROLE_MAP.get(entry.getKey()),childInfoList));
                            }

                            mGroupAdapter.setGroupList(groupInfoList);
                            mElvGroups.setAdapter(mGroupAdapter);
                        }

                        @Override
                        public void onResultFailure(int code, String msg) {

                        }
                    });
        }
    }

    private void initToolBar() {
        ((MainActivity) requireActivity()).showToolbarMenu();
        ((MainActivity) requireActivity()).showToolbarAvatar();
//        ((TextView) requireActivity().findViewById(R.id.toolbar_title)).setText("联系人");
    }

    /**
     * Called when the view previously created by {@link #onCreateView} has
     * been detached from the fragment.  The next time the fragment needs
     * to be displayed, a new view will be created.  This is called
     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
     * <em>regardless</em> of whether {@link #onCreateView} returned a
     * non-null view.  Internally it is called after the view's state has
     * been saved but before it has been removed from its parent.
     */
    @Override
    public void onDestroyView() {
        if (mFriendsCall.isExecuted()){
            mFriendsCall.cancel();
        }
        if (mGroupCall.isExecuted()) {
            mGroupCall.cancel();
        }
        mUnbinder.unbind();
        super.onDestroyView();
    }
}